package com.oriole.oauth2.server.config;

import com.oriole.common.constant.Constants;
import com.oriole.common.constant.ResultModel;
import com.oriole.common.constant.ResultStatus;
import com.oriole.common.util.FastJsonUtil;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/9/7 23:58
 * description:
 */
@Component
public class CaptchaFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        if ("POST".equals(request.getMethod()) && "/auth/login".equals(request.getRequestURI())) {
            String verifyCode = session.getAttribute("verifyCode").toString();
            if (!verifyCode.toLowerCase().equals(request.getParameter("captcha").toLowerCase())) {
                ResultModel<String> resultModel = new ResultModel<>(ResultStatus.FAIL, Constants.CAPTCHA_MSG);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.print(FastJsonUtil.toJsonString(resultModel));
                out.flush();
                out.close();
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
